////
////  SchemeProgramView_2.swift
////  vr
////
////  Created by 李旭峰 on 2020/8/5.
////
//
//import UIKit
//import WebKit
//import RxSwift
//import RxCocoa
//import FCUUID
//class SchemeProgramView_2: UIView {
//    var url:URL?
//    private var schemeId:String?
//    private var roomId:String?
//    private var vrType:Int?
//    weak var delegate:SchemeProgramViewDelegate?
//    var isNeedGoBack:Bool = true
//    var isNeedPopToRoot:Bool = false
//    var isNeedRightBarItem:Bool = false
//    let maskImageView = UIImageView(image: UIImage(named: "image_vrbg"))
//    let contentView = UIView()
//    var shareBaseUrl:String = ""
//    var tenantId:String = ""
//    var userId:String = "0"
//    private var roomIdStr:String = FCUUID.uuid()!
//    lazy var webView:UIWebView = {
//        var webView = UIWebView(frame: CGRect.zero)
//        webView.delegate = self
//        return webView
//    }()
//    let videoViewModel:AsmanVideoRecordViewModel = AsmanVideoRecordViewModel()
//    lazy var bridge:WebViewJavascriptBridge = {
//        let tempBridge = WebViewJavascriptBridge(self.webView)!
//        return tempBridge
//    }()
//
//    init(withUrl url:URL?) {
//        self.url = url
//        super.init(frame: CGRect.zero)
//        AsmanLiteManager.default.delegate = self
//        self.loadView()
//        self.viewDidLoad()
//    }
//    required init?(coder aDecoder: NSCoder) {
//        fatalError("init(coder:) has not been implemented")
//    }
//
//    func loadView(){
//        self.webView.frame = CGRect(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight)
//        self.maskImageView.frame = UIScreen.main.bounds
//        self.maskImageView.contentMode = .scaleToFill
//        self.maskImageView.layer.masksToBounds = true
//        self.contentView.backgroundColor = UIColor.purple
//        self.contentView.frame = UIScreen.main.bounds
//        self.addSubview(self.contentView)
//        self.addSubview(self.maskImageView)
//        self.contentView.addSubview(self.webView)
//    }
//
//    func viewDidLoad(){
//        if let tempUrl = self.url {
//            self.resetUrlPath(tempUrl)
//        }
//    }
//    func viewWillAppear(){
//    }
//    func viewDidAppear(){
//
//    }
//    func viewWillDisappear(){
//
//    }
//    func viewDidDisappear(){
//
//    }
//    deinit {
//        print("scheme program view did deinit")
//        let tempRoomIdStr = String.SwitchToString(AsmanLiteManager.default.roomId) ?? "-10000"
//        dPrintLog("VR Web View", "VR Web View - room id \(tempRoomIdStr),\(self.roomIdStr)")
//        if tempRoomIdStr == self.roomIdStr {
//            AsmanLiteManager.default.delegate = nil
//            if AsmanLiteManager.default.rtcStatus != .kInvalid {
//                AsmanLiteManager.default.exitRoom(withCallBack: nil)
//            }
//            AsmanLiteManager.default.deinitRtcRoom()
//        }
//    }
//
//    func resetUrlPath(_ url:URL){
//        DispatchQueue.main.async {
//            self.url = url
//            let tempParams = url.absoluteString.params()
//            if let tempRoomId = String.SwitchToString(tempParams["roomId"]) {
//                self.roomIdStr = tempRoomId
//            }
//            self.maskImageView.alpha = 1.0
//            self.maskImageView.isHidden = false
//            let webView = UIWebView(frame: CGRect.zero)
//            self.resetWebView(newWebView: webView)
//            let userAgent = self.webView.stringByEvaluatingJavaScript(from: "navigator.userAgent")
//            var tempUserAgent = userAgent ?? ""
//            let infoDictionary = Bundle.main.infoDictionary
//            let majorVersion:String = String.SwitchToString(infoDictionary?["CFBundleShortVersionString"]) ?? ""
//            let identifierString = "xiaoniuge"
//            if let range = tempUserAgent.range(of: identifierString) {
//                let location = tempUserAgent.distance(from: tempUserAgent.startIndex, to: range.lowerBound) - 1
//                tempUserAgent = String(tempUserAgent.prefix(location))
//            }
//            tempUserAgent += " \(identifierString)/\(majorVersion)"
//            UserDefaults.standard.register(defaults: ["UserAgent":tempUserAgent])
//
//            let tempWebView = UIWebView(frame: CGRect.zero)
//            self.resetWebView(newWebView: tempWebView)
//            self.initBridge()
//            let debutUserAgent = self.webView.stringByEvaluatingJavaScript(from: "navigator.userAgent") ?? ""
//            dPrintLog("设置之后 - user agent : \(debutUserAgent)")
//            DispatchQueue.main.async {
//                if let tempUrl = self.url {
//                    let request = URLRequest(url: tempUrl)
//                    self.webView.loadRequest(request)
//                }
//            }
//        }
//    }
//    func resetWebView(newWebView:UIWebView){
//        let oldWebView = self.webView
//        oldWebView.delegate = nil
//        oldWebView.removeFromSuperview()
//
//        self.webView = newWebView
//        self.webView.delegate = self
//        self.webView.frame = CGRect(x: 0, y: 0, width: kScreenWidth, height: kScreenHeight)
//        self.contentView.addSubview(self.webView)
//    }
//    func initBridge(){
//        self.bridge = WebViewJavascriptBridge(self.webView)!
//        self.bridge.setWebViewDelegate(self)
//    }
//    private func registerJSHandler(){
//        self.bridge.registerHandler("getVersion") { (params, callBack) in
//            var result:[String:Any] = [:]
//            result["code"] = "10000"
//            result["result"] = UIDevice.current.appVersion
//            callBack?(result)
//        }
//        // 唤起原生应用的分享
//        self.bridge.registerHandler("showSharePageView") {[weak self] (params, callBack) in
//            guard let _ = self else { return }
//            let callBackParams:[String:Any] = ["code":"10000"]
//            callBack?((callBackParams as NSDictionary).jsonString())
//        }
//        // 直接调起微信分享
//        self.bridge.registerHandler("shareWXMiniProgram") {[weak self] (params, callBack) in
//            guard let _ = self else { return }
//            let callBackParams:[String:Any] = ["code":"10000"]
//            callBack?((callBackParams as NSDictionary).jsonString())
//        }
//        // 调用原生应用的后退事件，无需参数。如果历史记录不为空则后退，如果历史记录为空，则关闭当前webview。
//        self.bridge.registerHandler("goBack") {[weak self] (params, callBack) in
//            guard let `self` = self else { return }
//            if self.isNeedGoBack && self.webView.canGoBack {
//                self.webView.goBack()
//            }else{
//                if AsmanLiteManager.default.rtcStatus != .kInvalid {
//                    // roomId , schemeId , vrtype
//                    var paramsStr = ""
//                    if let tempRoomId = AsmanLiteManager.default.roomId {
//                        paramsStr += (String.SwitchToString(tempRoomId) ?? "")
//                    }
//                    let urlParams = self.url?.absoluteString.params() ?? [:]
//                    if let tempSchemeId = String.SwitchToString(urlParams["schemeId"]) {
//                        if paramsStr.count >= 1 {
//                            paramsStr += ","
//                        }
//                        paramsStr += tempSchemeId
//                    }
//                    if let tempVrType = String.SwitchToString(urlParams["vrType"]) {
//                        if paramsStr.count >= 1 {
//                            paramsStr += ","
//                        }
//                        paramsStr += tempVrType
//                    }
//                    self.delegate?.onGoBack(paramsStr)
//                } else {
//                    self.delegate?.onGoBack("")
//                }
//            }
//            let callBackParams:[String:Any] = ["code":"10000"]
//            callBack?((callBackParams as NSDictionary).jsonString())
//        }
//        // 关闭webview，无需参数
//        self.bridge.registerHandler("closeNativeView") {[weak self] (params, callBack) in
//            guard let `self` = self else { return }
//            guard let tempUrl = self.url else { return }
//            if AsmanLiteManager.default.rtcStatus != .kInvalid {
//                // roomId , schemeId , vrtype
//                var paramsStr = ""
//                let urlParams = self.url?.absoluteString.params() ?? [:]
//                if let tempSchemeId = String.SwitchToString(urlParams["roomId"]) {
//                    if paramsStr.count >= 1 {
//                        paramsStr += ","
//                    }
//                    paramsStr += tempSchemeId
//                }else {
//                    if let tempRoomId = AsmanLiteManager.default.roomId {
//                        paramsStr += (String.SwitchToString(tempRoomId) ?? "0")
//                    }else {
//                        paramsStr += "0"
//                    }
//                }
//                if let tempSchemeId = String.SwitchToString(urlParams["schemeId"]) {
//                    if paramsStr.count >= 1 {
//                        paramsStr += ","
//                    }
//                    paramsStr += tempSchemeId
//                }else {
//                    paramsStr += ",0"
//                }
//                if let tempVrType = String.SwitchToString(urlParams["vrType"]) {
//                    if paramsStr.count >= 1 {
//                        paramsStr += ","
//                    }
//                    paramsStr += tempVrType
//                }else {
//                    paramsStr += ",0"
//                }
//                self.delegate?.onGoBack(paramsStr)
//            } else {
//                self.delegate?.onGoBack("")
//            }
//            let callBackParams:[String:Any] = ["code":"10000"]
//            callBack?((callBackParams as NSDictionary).jsonString())
//        }
//        // 弹出登陆页
//        self.bridge.registerHandler("showLoginView") {[weak self] (params, callBack) in
//            guard let _ = self else { return }
//            let callBackParams:[String:Any] = ["code":"10000"]
//            callBack?((callBackParams as NSDictionary).jsonString())
//        }
//        self.bridge.registerHandler("switchToDesignerShopView") {[weak self] (params, callBack) in
//            guard let `self` = self else { return }
//            guard let tempParams = params as? [String:Any], let designerId = String.SwitchToString(tempParams["designerId"]) else {
//                let callBackParams:[String:Any] = ["code":"-10000","msg":"缺少设计师ID"]
//                callBack?((callBackParams as NSDictionary).jsonString())
//                return
//            }
//            self.delegate?.switchToDesignerShopView(designerId)
//            let callBackParams:[String:Any] = ["code":"10000"]
//            callBack?((callBackParams as NSDictionary).jsonString())
//        }
//        // 报价单页
//        self.bridge.registerHandler("switchToQuotationView") {[weak self] (params, callBack) in
//            guard let `self` = self else { return }
//            guard let tempParams = params as? [String:Any], let decorationInfo = tempParams["decorationInfo"] as? [String:Any] else {
//                let callBackParams:[String:Any] = ["code":"-10000","msg":"缺少方案ID"]
//                callBack?((callBackParams as NSDictionary).jsonString())
//                return
//            }
//            guard let schemeId = String.SwitchToString(decorationInfo["schemeId"]) else {
//                let callBackParams:[String:Any] = ["code":"-10000","msg":"缺少方案ID"]
//                callBack?((callBackParams as NSDictionary).jsonString())
//                return
//            }
//            let hotspots = decorationInfo["hotspots"] as? [String:Any] ?? [:]
//            let workId = String.SwitchToString(decorationInfo["workId"])
//            self.delegate?.routeToDecorateDetail(with: schemeId, workId: workId, hotspots: hotspots)
//            let callBackParams:[String:Any] = ["code":"10000"]
//            callBack?((callBackParams as NSDictionary).jsonString())
//        }
//        self.bridge.registerHandler("nativationToGoodsDetail") {[weak self] (params, callBack) in
//            guard let _ = self else { return }
//            DispatchQueue.main.async{
//                let callBackParams:[String:Any] = ["code":"10000"]
//                callBack?((callBackParams as NSDictionary).jsonString())
//            }
//        }
//        // 腾讯云事件
//        self.bridge.registerHandler("callAppTrtc") {[weak self] (jsParams, callBack) in
//            dPrintLog("VR Web View", "call app trtc - start call")
//            DispatchQueue.main.async {
//                guard let `self` = self else { return }
//                guard let `jsParams` = jsParams as? [String:Any] else {
//                    callBack?(["code":"-10000","result":false,"msg":"参数缺失"])
//                    return
//                }
//                guard let actionType = String.SwitchToString(jsParams["type"]) else {
//                    callBack?(["code":"-10000","result":false,"msg":"参数缺失"])
//                    return
//                }
//                switch actionType {
//                case "joinRoom":
//                    dPrintLog("VR Web View", "call app trtc - will join room")
//                    DeviceAuthorizationUtil.audioAuthorization({[weak self] in
//                        guard let `self` = self else { return }
//                        switch AsmanLiteManager.default.rtcStatus {
//                        case .kInvalid:
//                            let url = self.url
//                            let urlParams = url?.absoluteString.cx_urlQueryDict() ?? [:]
//                            let schemeId = String.SwitchToString(urlParams["schemeId"]) ?? ""
//                            let liteInfo = jsParams["params"] as? [String : Any]
//                            if liteInfo == nil {
//                                callBack?(["code":"-3316","result":false,"msg":"参数缺失"])
//                                return
//                            }
//                            guard let userId = String.SwitchToString(liteInfo!["userId"]),
//                                let roomId = String.SwitchToString(liteInfo!["roomId"])?.decimal.uint32Value,
//                                let userSig = String.SwitchToString(liteInfo!["userSig"]),
//                                let sdkAppId = String.SwitchToString(liteInfo!["sdkAppId"])?.decimal.uint32Value
//                                else {
//                                callBack?(["code":"-3316","result":false,"msg":"参数缺失"])
//                                return
//                            }
//                            if let tempRoomId = String.SwitchToString(roomId) {
//                                self.roomIdStr = tempRoomId
//                            }
//                            AsmanLiteManager.default.initRtcRoom2(withRoomId: roomId, schemeId: schemeId, params: [:]) { (success, error, code) in
//                                if !success {
//                                    callBack?(["code":"-10000","result":false,"msg":"加入房间异常"])
//                                    return
//                                }
//                                AsmanLiteManager.default.enterRoom(sdkAppId: sdkAppId, userSig: userSig, userId: userId, roomId: roomId) {[weak self] (success, error, errorCode) in
//                                    guard let _ = self else { return }
//                                    if success {
//                                        dPrintLog("VR Web View", "call app trtc - will join room")
//                                        callBack?(["code":"10000","result":true,"msg":""])
//                                    }else {
//                                        callBack?(["code":String.SwitchToString(errorCode) ?? "-10000","result":false,"msg":""])
//                                    }
//                                }
//                            }
//                        case .kDidInit,.kDidEnter:
//                            callBack?(["code":"10000","result":true,"msg":""])
//                            if AsmanLiteManager.default.isUserJoinRoom {
//                                let userId = self.userId
//                                self.onRemoteUserEnterRoom(userId)
//                            }
//                        default:break
//                        }
//                    }) { (isFirst) in
//                        if isFirst {
//                            let callBackParams:[String:Any] = ["code":"-10000","result":false,"msg":"麦克风权限获取失败"]
//                            callBack?((callBackParams as NSDictionary).jsonString())
//                        }else {
//                            let alertController = UIAlertController(title: "", message: "请在iPhone的“设置-隐私-麦克风”选项中，允许牛牛搭访问你的手机麦克风。", preferredStyle: .alert)
//                            let cancelAction = UIAlertAction(title: "好的", style:.cancel) { (_) in }
//                            let sureAction = UIAlertAction(title: "设置", style: .default) { (action) in
//                                if let tempOpenUrl = URL(string: UIApplication.openSettingsURLString) {
//                                    DispatchQueue.main.async {
//                                        UIApplication.shared.open(tempOpenUrl, options: [:]) { (granted) in }
//                                    }
//                                }
//                            }
//                            alertController.addAction(cancelAction)
//                            alertController.addAction(sureAction)
//                            UIApplication.shared.keyWindow?.rootViewController?.present(alertController, animated: true, completion: nil)
//                            let callBackParams:[String:Any] = ["code":"-10000","result":false,"msg":"用户未授权"]
//                            callBack?((callBackParams as NSDictionary).jsonString())
//                            return
//                        }
//                    }
//                case "leaveRoom":
//                    print("VR Web View - leave room before : ")
//                    let tempRoomIdStr = String.SwitchToString(AsmanLiteManager.default.roomId) ?? "-10000"
//                    dPrintLog("VR Web View", "VR Web View - room id  before \(tempRoomIdStr),\(self.roomIdStr)")
//                    AsmanLiteManager.default.exitRoom { (success, error, result) in
//                        print("VR Web View - leave room : \(success ? "success" : "fail")")
//                        let tempRoomIdStr = String.SwitchToString(AsmanLiteManager.default.roomId) ?? "-10000"
//                        dPrintLog("VR Web View", "VR Web View - room id \(tempRoomIdStr),\(self.roomIdStr)")
//                        if !success {
//                            callBack?(["code":"-10000","result":result,"msg":""])
//                            return
//                        }
//                        callBack?(["code":"10000","result":true,"msg":""])
//                        AsmanLiteManager.default.deinitRtcRoom()
//                    }
////                    AsmanLiteManager.default.exitRoom(withCallBack: nil)
//                default:break
//                }
//            }
//            }
//    }
//    private func eveJsCode(params:[String:Any]){
//        dPrintLog("VR Web View", "VR Web View - notify trtc \(params.description)")
//        self.bridge.callHandler("notifyTrtcH5", data: params) { (response) in }
//    }
//
//    private func onJoinRoom(jsParams:[String:Any],callBack:WVJBResponseCallback?){
//
//    }
//}
//extension SchemeProgramView_2 : UIWebViewDelegate {
//    func webViewDidStartLoad(_ webView: UIWebView) {
//        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 2) {
//            self.maskImageView.alpha = 1
//            self.maskImageView.isHidden = false
//            UIView.animate(withDuration: 1.5, delay: 0, options: [], animations: {
//                self.maskImageView.alpha = 0.01
//            }) { (isFinished) in
//                self.maskImageView.isHidden = true
//            }
//        }
//    }
//    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
////        self.resetUrlPath(self.url!)
//    }
//    func webViewDidFinishLoad(_ webView: UIWebView) {
//        self.registerJSHandler()
//    }
//}
//extension SchemeProgramView_2 : AsmanLiteDelegate {
//    func onUserEnterRoom(){
//        dPrintLog("TRTC - 自己进入房间")
//        //AsmanLiteManager.default.rtcAnswer()
//    }
//    func onUserLeaveRoom(){
//        AsmanLiteManager.default.deinitRtcRoom()
//    }
//    func onRemoteUserEnterRoom(_ userId: String){
//        var params:[String:Any] = [:]
//        params["type"] = "onRemoteUserEnterRoom"
//        params["params"] = ["userId":userId]
//        self.eveJsCode(params: params)
//    }
//    func onRemoteUserLeaveRoom(_ userId: String, reason: Int){
//        var params:[String:Any] = [:]
//        params["type"] = "onRemoteUserLeaveRoom"
//        params["params"] = ["userId":userId]
//        self.eveJsCode(params: params)
//    }
//}
